package com.woyowodaows.activity.home;


import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.woyowodaows.R;
import com.woyowodaows.activity.MainActivity;
import com.woyowodaows.bean.home.BannerInfoBean;
import com.woyowodaows.bean.home.BannerInfoDataBean;
import com.woyowodaows.request.HttpAsyncTask;
import com.woyowodaows.request.HttpRequestListener;
import com.woyowodaows.request.InterfaceUrl;
import com.woyowodaows.utils.BitmapUtil;
import com.woyowodaows.utils.DateUtil;
import com.woyowodaows.utils.ImageLoaderUtlis;
import com.woyowodaows.utils.SPUtils;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pub.devrel.easypermissions.EasyPermissions;


/**
 * Created by Administrator on 2017/7/5.
 * 启动页面
 * 修改时间2018-3-31 haiwei
 */

public class SplashActivity extends FragmentActivity implements EasyPermissions.PermissionCallbacks {


    @BindView(R.id.splash_iv)
    ImageView splashIv;
    @BindView(R.id.splash_ll)
    LinearLayout splashLl;
    private String imageUrl;
    private String aurl;
    private boolean isGoto = true;
    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    //监听图片是否加载成功和失败
                    Glide.with(SplashActivity.this)
                            .load(imageUrl)
                            .asBitmap()
                            .error(R.mipmap.icon_splash)
                            .into(new SimpleTarget<Bitmap>() {
                                @Override
                                public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                    SPUtils.put(SplashActivity.this, SPUtils.SAVE_FLASH_ICON, BitmapUtil.saveImageToGallery(SplashActivity.this, resource, "splash-" + DateUtil.getCurrentDate()));
                                }

                                @Override
                                public void onLoadFailed(Exception e, Drawable errorDrawable) {
                                    super.onLoadFailed(e, errorDrawable);
                                }
                            });

                    break;
                case 1:
                    if (isGoto) {
                        startMainActivity();
                    }
                    break;

            }
        }
    };

    public void startMainActivity() {
        Intent mainIntent = new Intent(SplashActivity.this, MainActivity.class);
        SplashActivity.this.startActivity(mainIntent);
        SplashActivity.this.finish();
        overridePendingTransition(R.anim.zoomin,
                R.anim.zoomout);
    }

    /**
     * 需要进行检测的权限数组
     */
    protected String[] needPermissions = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,Manifest.permission.READ_PHONE_STATE
    };


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SPUtils.put(SplashActivity.this, SPUtils.SAVE_FLASH_IS, false);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_splash);
        ButterKnife.bind(this);
//        loadFlieBitmap();
        getNetworkImage();
        if (!EasyPermissions.hasPermissions(this, needPermissions)) {//检查是否获取该权限
            EasyPermissions.requestPermissions(this, "此应用需要您授权当前权限！", 200, needPermissions);
        } else {
            handler.sendEmptyMessageDelayed(1, 2000);
        }

    }

    //获取网络图片
    private void getNetworkImage() {
        Map<String, Object> mapParameter = new HashMap<>();
        //offset:0启动页 1首页广告 2个人中心
        mapParameter.put("offset", "0");
        HttpAsyncTask.getInstance().onPostParam(this, "", false, InterfaceUrl.BANNDER, BannerInfoDataBean.class, mapParameter, new HttpRequestListener() {
            @Override
            public void onSuccess(Object result) {
                if (result != null) {
                    BannerInfoDataBean splashBean = (BannerInfoDataBean) result;
                    if (splashBean.getResult() == HttpAsyncTask.SUCCESS) {
                        if (splashBean.getData() != null && splashBean.getData().size() > 0 ) {
                            imageUrl = splashBean.getFileUrl() + splashBean.getData().get(0).getPic();
                            ImageLoaderUtlis.displayLocalImage(SplashActivity.this, imageUrl, R.mipmap.icon_splash, splashIv);
                        }else {
                            splashIv.setImageResource(R.mipmap.icon_splash);
                        }
                    }
                }
            }

            @Override
            public void onError(String message) {
                splashIv.setImageResource(R.mipmap.icon_splash);
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //把申请权限的回调交由EasyPermissions处理
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }


    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        handler.sendEmptyMessageDelayed(1, 2000);
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        finish();
    }


    //加载网络缓存图片
    private void loadFlieBitmap() {
        String filePath = (String) SPUtils.get(SplashActivity.this, SPUtils.SAVE_FLASH_ICON, "");
        String saveImageUrl = (String) SPUtils.get(SplashActivity.this, SPUtils.SAVE_FLASH_IMAGE_URK, "");
        if (TextUtils.isEmpty(filePath)) {
            //判断保存在本地的图片如果等于空  而网络图片URL的不等于空则加载网络图片 （防止图片保存失败）
            if (TextUtils.isEmpty(saveImageUrl)) {
                splashIv.setImageResource(R.mipmap.icon_splash);
            } else {
                ImageLoaderUtlis.displayLocalImage(SplashActivity.this, saveImageUrl, R.drawable.ic_launcher_background, splashIv);
            }
        } else {
            ImageLoaderUtlis.displayLocalImage(SplashActivity.this, filePath, R.drawable.ic_launcher_background, splashIv);
        }
    }

    @OnClick(R.id.splash_ll)
    public void onViewClicked() {
        if (!TextUtils.isEmpty(aurl)) {//判断跳转地址是否为空
            SPUtils.put(SplashActivity.this, SPUtils.SAVE_FLASH_IS, true);
            isGoto = false;
            startMainActivity();
        }
    }
}
